package com.fz.controller;

import com.fz.mapper.StudentMapper;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

/**
 * Created by ZCY on 2018-01-25.
 *  注：Controller是控制器的意思
 */
@Controller
public class HelloController {
    @RequestMapping("/abc") @ResponseBody
    public void abc(PrintWriter out){
        out.write("hello----world");
        System.out.println("hello---");
    }

   /*根据id进行删除数据库中的数据*/
   @RequestMapping("/del")
   public String del(int id){
       InputStream is = null;
       try {
           is = Resources.getResourceAsStream("mybatis-config.xml");
       } catch (IOException e) {
           e.printStackTrace();
       }
       SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(is);
       SqlSession session = sf.openSession();
       StudentMapper sm = session.getMapper(StudentMapper.class);
       sm.delById(id);
       session.commit();//提交
     return "redirect:/test";
   }

    @RequestMapping("/test")
    public ModelAndView test(){
        ModelAndView mv = new ModelAndView("test");
        mv.addObject("name","李四四");
        InputStream is = null;
        try {
            is = Resources.getResourceAsStream("mybatis-config.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }
        SqlSessionFactory sf = new SqlSessionFactoryBuilder().build(is);
        SqlSession session = sf.openSession();
       StudentMapper sm = session.getMapper(StudentMapper.class);
       mv.addObject("list",sm.query());



        return mv;
    }




}
